<template>
  <div class="layout-main-conent">
    <a-card
      :bordered="false"
      style="margin-bottom: 15px"
      :bodyStyle="{ paddingBottom: '0' }"
    >
      <a-form :labelCol="{ span: 6, offset: 0 }" :wrapper-col="{ span: 18 }">
        <a-row :gutter="16">
          <a-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
            <a-form-item label="所属应用：">
              <a-select
                placeholder="请选择"
                v-model:value="searchModelRef.appId"
                :options="appList"
                @change="handleAppChange"
              >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6"> </a-col>
          <a-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6"> </a-col>
          <a-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
            <div class="text-align-right" style="padding-bottom: 24px">
              <a-button type="primary" @click="searchFormSubmit">查询</a-button>
              <a-button style="margin-left: 8px" @click="searchResetFields"
                >重置</a-button
              >
            </div>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card :bordered="false" class="table-card">
      <template #extra>
        <a-button type="primary" @click="() => setCreateFormVisible(true)"
          >新建</a-button
        >
      </template>
      <a-table
        row-key="id"
        :columns="columns"
        :data-source="list"
        :loading="loading"
        :pagination="false"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-button type="link" @click="() => detailUpdateData(record)"
              >编辑</a-button
            >
            <a-button
              type="link"
              @click="() => deleteTableData(record)"
              class="delete-button"
              >删除</a-button
            >
          </template>
          <template v-else-if="column.key === 'enableStatus'">
            <a-switch
              v-model:checked="record.enableStatus"
              checked-children="ON"
              un-checked-children="OFF"
              @change="switchStatus(record)"
            />
          </template>
        </template>
      </a-table>
    </a-card>
    <create-form
      :visible="createFormVisible"
      :onCancel="() => setCreateFormVisible(false)"
      :onSubmitLoading="createSubmitLoading"
      :onSubmit="createSubmit"
      :appId="searchModelRef.appId"
    />

    <update-form
      v-if="updateFormVisible"
      :visible="updateFormVisible"
      :values="updateRoleData"
      :onCancel="() => updataFormCancel()"
      :onSubmitLoading="updateSubmitLoading"
      :onSubmit="updateSubmit"
    />
    <delete-modal
      :visible="deleteVisible"
      :onCancel="() => (deleteVisible = false)"
      :onSubmit="deleteSubmit"
    />
  </div>
</template>
<script lang="ts" setup>
import { onMounted, ref } from "vue";
import { message, Modal } from "ant-design-vue";

import CreateForm from "./components/CreateForm.vue";
import UpdateForm from "./components/UpdateForm.vue";
import { TableListItem } from "./data";
import {
  queryTreeList,
  switchData,
  createData,
  updateData,
  removeData,
} from "./service";
import { queryAppList } from "@/views/roleManager/service";
import DeleteModal from "@/views/component/DeleteModal.vue";

const deleteVisible = ref(false);
const selectedRecord = ref({});
const deleteSubmit = async () => {
  const res = await removeData([selectedRecord.value.id]);
  if (res.success) {
    getList();
    message.success("删除成功");
  }
  deleteVisible.value = false;
};
// 列表字段
const columns = [
  {
    title: "名称",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "类型",
    dataIndex: "type",
    key: "type",
    customRender: ({ text }: { text: any }) => {
      if (text === "catalog") {
        return "目录";
      } else if (text === "menu") {
        return "菜单";
      } else if (text === "button") {
        return "功能按钮";
      } else if (text === "page") {
        return "页面";
      }
    },
  },
  {
    title: "地址",
    dataIndex: "path",
    key: "path",
  },
  {
    title: "权限标识",
    dataIndex: "code",
    key: "code",
  },
  {
    title: "状态",
    dataIndex: "enableStatus",
    key: "enableStatus",
  },
  {
    title: "操作",
    key: "action",
    width: 240,
  },
];

const appList = ref([]);
const getAppList = async (): Promise<void> => {
  const res = await queryAppList();
  if (res.success) {
    if (res.data.length > 0) {
      res.data.forEach((ele) => {
        const obj = {
          label: ele.name,
          value: ele.id + "",
        };
        appList.value.push(obj);
      });
      searchModelRef.value.appId = res.data[0].id + "";
      getList();
    }
  }
};
// 获取数据
const list = ref([]);
const loading = ref<boolean>(true);
const getList = async (): Promise<void> => {
  loading.value = true;
  const params = {
    showAsTreeFlag: true,
    showleafNodeFlag: true,
    ...searchModelRef.value,
  };
  const res = await queryTreeList(params);
  if (res.success) {
    list.value = recursiveDelete(res.data);
  }
  loading.value = false;
};
const switchStatus = async (record) => {
  const req = {
    id: record.id,
    enableStatus: record.enableStatus ? "1" : "0",
  };
  const res = await switchData(req);
  if (res.success) {
    message.success("状态修改成功！");
  }
};
const recursiveDelete = (arr) => {
  for (let i = 0; i < arr.length; i++) {
    arr[i].enableStatus = arr[i].enableStatus === "1";
    if (arr[i].children.length <= 0) {
      delete arr[i].children;
    } else {
      recursiveDelete(arr[i].children);
    }
  }
  return arr;
};
// 表单值
const searchModelRef = ref({
  appId: "",
});
// 搜索
const searchFormSubmit = async () => {
  getList();
};
const searchResetFields = async () => {
  searchFormSubmit();
};
// 新增弹框 - visible
const createFormVisible = ref<boolean>(false);
const setCreateFormVisible = (val: boolean) => {
  createFormVisible.value = val;
};
// 新增弹框 - 提交 loading
const createSubmitLoading = ref<boolean>(false);
// 新增弹框 - 提交
const createSubmit = async (values: Omit<TableListItem, "id">) => {
  createSubmitLoading.value = true;
  const res = await createData(values);
  if (res.success) {
    setCreateFormVisible(false);
    message.success("新增成功！");
    getList();
  }
  createSubmitLoading.value = false;
};
// 编辑弹框 data
const updateRoleData = ref({});
const detailUpdateData = (record: Object) => {
  setUpdateFormVisible(true);
  updateRoleData.value = record;
};
// 编辑弹框 - visible
const updateFormVisible = ref<boolean>(false);
const setUpdateFormVisible = (val: boolean) => {
  updateFormVisible.value = val;
};
const updataFormCancel = () => {
  setUpdateFormVisible(false);
};
// 编辑弹框 - 提交 loading
const updateSubmitLoading = ref<boolean>(false);
// 编辑弹框 - 提交
const updateSubmit = async (values: TableListItem) => {
  updateSubmitLoading.value = true;
  const res = await updateData(values);
  if (res.success) {
    updataFormCancel();
    message.success("编辑成功！");
    getList();
  }
  updateSubmitLoading.value = false;
};
// 删除
const deleteTableData = (record) => {
  deleteVisible.value = true;
  selectedRecord.value = record;
  // Modal.confirm({
  //     title: '删除',
  //     content: '确定删除吗？',
  //     okText: '确认',
  //     cancelText: '取消',
  //     onOk: async () => {
  //         const ids = [id]
  //         const res = await removeData(ids)
  //         if (res.success) {
  //             message.success('删除成功！');
  //             getList();
  //         }
  //     }
  // });
};

const handleAppChange = () => {
  getList();
};

onMounted(() => {
  getAppList();
});
</script>
<style scoped lang="less">
.delete-button {
  color: red;
}
.role-manager {
  margin-right: 20px;
}
.table-card {
  :deep(.ant-card-body) {
    padding: 0px 24px 24px 24px;
  }
}
:deep(.ant-card-head) {
  border: none;
}
</style>
